/** 
 * 2011-10-10 下午05:49:33 
 * UdpProtocolDecoder.java 
 * author:sunb 
 */
package com.u6.udp.netty;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import com.lamfire.utils.JSON;

/**
 * @author sunbin
 * 
 */
public class UdpProtocolDecoder extends FrameDecoder {

	protected Object decode(ChannelHandlerContext context, Channel channel, ChannelBuffer source) throws Exception {
		// TODO Auto-generated method stub
		if (source.readableBytes() < UdpMessage.HEADER_SIZE) {
			return null;
		}

		source.markReaderIndex();

		try {
			
			short messageID = source.readShort();
			System.out.println(messageID);
			short type = source.readShort();
			long sendUid = source.readLong();
			long receiveUid = source.readLong();

			int contentLen = source.readInt();
			if (source.readableBytes() < contentLen) {
				source.resetReaderIndex();
				return null;
			}

			byte[] data = new byte[contentLen];
			source.readBytes(data);
			UdpMessage udpMessage=new  UdpMessage(messageID, type, sendUid, receiveUid, contentLen, data) ;
			System.out.println(JSON.toJsonString(udpMessage));
			
			return udpMessage ;
		} catch (Exception e) {
			source.resetReaderIndex();
		}

		return null;
	}

}
